﻿using System.ComponentModel;
using K9Nano.Dependency;
using K9Nano.Extensions;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.Dict;

public class DefaultDictResolverFactory(IServiceProvider serviceProvider) : IDictResolverFactory, IScopedDependency
{
    public virtual IDictResolver? Create(string name)
    {
        return serviceProvider.GetKeyedService<IDictResolver>(name);
    }

    public virtual KeyValuePair<string, string>[] GetAllDictMeta()
    {
        var ioc = serviceProvider.GetRequiredService<IIocHelper>();
        var resolvers = ioc.GetRegisteredTypes<IDictResolver>();
        return resolvers
            .Select(GetResolverMeta)
            .ToArray();
    }

    private static KeyValuePair<string, string> GetResolverMeta(Type type)
    {
        var name = type.TryGetCustomAttribute<ServiceKeyNameAttribute>(false, out var nameAttr)
            ? nameAttr!.Key: type.Name;
       var description = type.TryGetCustomAttribute<DescriptionAttribute>(false, out var desAttr)
            ? desAttr!.Description : type.Name;
        return new KeyValuePair<string, string>(name, description);
    }
}
